package com.zw.re.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by zwz
 * date 2016/11/29
 * project com.zw.re.service
 */
@Service
public class ListOpt {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource(name = "jackson2JsonRedisSerializer")
    private RedisSerializer jackson2JsonRedisSerializer;
    /**
     * 插入一个集合
     * @param key
     * @param object
     * @return
     */
    public Long insertAll(Object key, List object) {
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate.opsForList().rightPushAll(key, object);
    }

    public Long insert(Object key, Object object) {
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate.opsForList().rightPush(key, object);
    }

    /**
     * 查询所有的
     * @param key
     * @return
     */
    public List queryAll(Object key) {
        redisTemplate.setValueSerializer(redisTemplate.getDefaultSerializer());
        return redisTemplate.opsForList().range(key, 0L, size(key));
    }

    /**
     * 获取指定下标的值
     * @param key
     * @param hKey
     * @return
     */
    public Object queryIndex(Object key, Long hKey) {
        redisTemplate.setValueSerializer(redisTemplate.getDefaultSerializer());
        return redisTemplate.opsForList().index(key, hKey);
    }

    /**
     * 根据起始和结束位置查询出一个集合
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List queryStep(Object key, long start, long end) {
        redisTemplate.setValueSerializer(redisTemplate.getDefaultSerializer());
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 获取list长度
     * @param key
     * @return
     */
    public Long size(Object key) {
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 根据index 删除
     * @param key
     * @param index
     */
    public Long delete(Object key, long index) {
        return redisTemplate.opsForList().remove(key, index, queryIndex(key, index));
    }

}
